/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.lucava.boatskeeper.server.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import org.lucava.boatskeeper.server.entity.Category;
import org.lucava.boatskeeper.shared.dto.CategoryDto;

/**
 *
 * @author glenn
 */
public class CategoryDao {

    EntityManager em;

    public CategoryDao(EntityManager em) {
        this.em = em;
    }

    public CategoryDto toDto(Category entity) {
        CategoryDto c = new CategoryDto(entity.getCategoryId().intValue(), entity.getCategoryName());
        return c;
    }

    public Category fromDto(CategoryDto dto) {


        Category entity = new Category();
        if (dto.getId() != null) {
            entity.setCategoryId(dto.getId().shortValue());
        }
        entity.setCategoryName(dto.getName());

        return entity;
    }

    public void add(CategoryDto dto) {

        try {
            EntityTransaction t = em.getTransaction();
            try {
                t.begin();
                em.persist(fromDto(dto));
                t.commit();
            } finally {
                if (t.isActive()) {
                    t.rollback();
                }
            }
        } finally {
            em.close();
        }
    }

    public void save(CategoryDto b) {
        categories.get(b.getId()).setName(b.getName());
    }

    public void delete(CategoryDto b) {

        categories.remove(b.getId());
    }

    public CategoryDto get(Integer id) {
        return categories.get(id);
    }

    public List<CategoryDto> getAll() {

        return new ArrayList<CategoryDto>(categories.values());
    }
}
